﻿using AutoMapper;
using BaseData.Domain;
using BaseData.ErrorCode;
using BaseData.Infrastructure.DTO;
using BaseData.Infrastructure.Interfaces;
using CSRedis;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BaseData.Infrastructure.Depart
{
    public class DepartService : IDepartService
    {
        private readonly IBaseRepository<Depts> depRep;
        private readonly IMapper mapper;
        private readonly IBaseRepository<Users> userRep;
        private readonly CSRedisClient redis;
        private readonly RedisService<Depts> deptredis;

        public DepartService(IBaseRepository<Depts> depRep,IMapper mapper,IBaseRepository<Users> userRep,CSRedisClient redis,RedisService<Depts> deptredis)
        {
            this.depRep = depRep;
            this.mapper = mapper;
            this.userRep = userRep;
            this.redis = redis;
            this.deptredis = deptredis;
        }
        /// <summary>
        /// 添加部门
        /// </summary>
        /// <param name="depts"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> AddDepart(Depts depts)
        {
            depts.DeptState = true;
            depts.MemberCount = 100;
            depts.UpdDate = DateTime.Now;
            var res = await depRep.AddAsync(depts);
            return res;
        }
        /// <summary>
        /// 单删除部门
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> DelDept(int id)
        {
            var res = await depRep.DelAsync(id);
            return res;
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> DelDeptAll(string ids)
        {
            var deplist = ids.Split(',').Select(i=>Convert.ToInt32(i)).ToList();
            var res = 0;
            foreach (var item in deplist)
            {
                await depRep.DelAsync(item);
                res++;
            }
            return res;
        }

        /// <summary>
        /// 显示部门下拉框
        /// </summary>
        /// <returns></returns>
        public async Task<List<Depts>> GetAllDepts()
        {
            //var redisDto = await redis.GetAsync<List<Depts>>("Depts");
            //if(redisDto!=null)
            //{
            //    return redisDto;
            //}
            //else
            //{
            //    var res = await depRep.GetAll().Where(x => x.ParentId == 0).ToListAsync();
            //    redisDto = res;
            //    var result = await redis.SetAsync("Depts", res);
            //}

            List<Depts> depts = await deptredis.GetListAsync("Departs",async () =>
            {
                var depts = await depRep.GetAll().Where(x => x.ParentId == 0).ToListAsync();
                return depts;
            },300);
            return depts;
        }
        /// <summary>
        /// 显示部门级联
        /// </summary>
        /// <param name="parentid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<TreeItem>> GetDepartTree(int parentid)
        {
            var res = await depRep.GetAll().Where(x => x.ParentId == parentid).ToListAsync();
            List<TreeItem> treeitem = new List<TreeItem>();
            foreach (var item in res)
            {
                var tree =  new TreeItem()
                {
                    value = item.DeptId,
                    label = item.DeptName,
                    children = await GetDepartTree(item.DeptId)
                };
                treeitem.Add(tree);
            }
            return treeitem;
        }

        /// <summary>
        /// 显示部门列表
        /// </summary>
        /// <param name="index"></param>
        /// <param name="size"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<PaggingResult<List<DeptDto>>> GetDeptPage(int index, int size, string? name)
        {
            var res = await  depRep.GetAll().ToListAsync();
            if(!string.IsNullOrEmpty(name))
            {
                res = res.Where(x=>x.DeptName.Contains(name)).ToList();
            }
            int c = res.Count();
            int p = (int)Math.Ceiling(c * 1.0 / size);
            res = res.OrderBy(x=>x.DeptId).Skip((index-1)*size).Take(size).ToList();
            var dto = mapper.Map<List<DeptDto>>(res);
            foreach(var item in dto)
            {
                item.UserName = userRep.GetAll().FirstOrDefault(x=>x.UsersId==item.UserId)?.UserName;
            }
            return new PaggingResult<List<DeptDto>>
            {
                Data = dto,
                Count = c,
                Pages = p,
            };
        }
        /// <summary>
        /// 设置状态
        /// </summary>
        /// <param name="deptId"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> UpdateState(int deptId, bool state)
        {
            var res = await depRep.GetById(deptId);
            res.DeptState = state;
            var result = await depRep.UpdateAsync(res);
            return result;
        }

        /// <summary>
        /// 修改部门
        /// </summary>
        /// <param name="depts">实体</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<int> UpdDept(Depts depts)
        {
            depts.DeptState = true;
            depts.MemberCount = 100;
            depts.UpdDate = DateTime.Now;
            var res = await depRep.UpdateAsync(depts);
            return res;
        }
    }
}
